package com.CuiChangHe.studentmanager.service.login.impl;

import com.CuiChangHe.studentmanager.entity.login.Login;
import com.CuiChangHe.studentmanager.entity.login.LoginReturnMsg;
import com.CuiChangHe.studentmanager.entity.login.Logout;
import com.CuiChangHe.studentmanager.entity.login.UserData;
import com.CuiChangHe.studentmanager.dao.UserDao;
import com.CuiChangHe.studentmanager.mapper.UserMapper;
import com.CuiChangHe.studentmanager.service.login.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description :用户登录业务实现
 * @Author :崔昌赫
 * @Date : 2021/11/16
 */
@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {

    private UserMapper mapper;

    @Autowired
    public void setMapper(UserMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    @Transactional(readOnly = true)
    public LoginReturnMsg login(Login login) {
        log.info("接收到登录请求.login:{}",login);
        LoginReturnMsg returnMsg = new LoginReturnMsg();
        if(login==null){
            returnMsg.setCode(50000);
            log.warn("登录失败!传入参数为空!");
            returnMsg.setMessage("传入参数为空!");
            return returnMsg;
        }
        if(login.getUsername().equals("")){
            returnMsg.setCode(50000);
            log.warn("登录失败!用户名为空!login:{}",login);
            returnMsg.setMessage("用户名为空!");
            return returnMsg;
        }
        if(login.getPassword().equals("")){
            returnMsg.setCode(50000);
            log.warn("登陆失败!密码为空!login:{}",login);
            returnMsg.setMessage("密码为空!");
            return returnMsg;
        }
        log.info("开始查找数据库...login:{}",login);
        UserDao userInfoByUserName = mapper.getUserInfoByUserName(login.getUsername());
        if (userInfoByUserName==null){
            returnMsg.setCode(50000);
            log.warn("未找到该用户，请检查您的账户是否正确!");
            returnMsg.setMessage("查找数据库失败!返回为空！");
            return returnMsg;
        }
        if(!userInfoByUserName.getUsername().equals(login.getUsername()) || !userInfoByUserName.getPassword().equals(login.getPassword())){
            returnMsg.setCode(50000);
            log.warn("登陆失败!账号或密码错误!login:{},查找信息:{}",login,userInfoByUserName);
            returnMsg.setMessage("登录失败!账号或密码错误!");
            return returnMsg;
        }
        log.info("登陆成功!login:{},查找信息:{}",login,userInfoByUserName);
        returnMsg.setCode(20000);
        returnMsg.setData(new UserData(userInfoByUserName.getToken()));
        return returnMsg;
    }

    @Override
    public Logout logout() {
        return new Logout(20000,"success");
    }
}
